package com.wzy.facetextview;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;

import com.wzy.facetextview.Utils.CommonURLClickHelper;
import com.wzy.facetextview.Utils.TextLinkClickSpan;
import com.wzy.facetextview.Utils.URLClickListener;
import com.wzy.facetextview.widget.FaceTextView;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "wang.MainActivity";
    Context mContext = MainActivity.this;
    private TextLinkClickSpan mClickSpan;
    private TextView commonTextView;
    private FaceTextView faceTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String faceAndUrlMessage = "带表情图片和超链接：<img src=\"http://www.baidu.com/static/image/smiley/face/001.gif\" border=\"0\" alt=\"\" />" +
                "<img src=\"http://www.baidu.com/static/image/smiley/face/001.gif\" border=\"0\" alt=\"\" />" +
                "你对自己身份证的照片满意吗？ " +
                "来自百度 http://www.baidu.com" +
                "<img src=\"http://www.baidu.com/static/image/smiley/vivo/003.gif\" border=\"0\" alt=\"\" />";
        faceTextView = (FaceTextView) findViewById(R.id.face_text);
        faceTextViewWithUrlAndFace(faceAndUrlMessage);


        commonTextView = (TextView) findViewById(R.id.common_text);
        String commonMessage = "普通的TextView：http://www.baidu.com";
        String url = "http://www.baidu.com";
        commonTextViewWithUrl(commonMessage, url);
    }

    // 显示带表情图片、URL
    private void faceTextViewWithUrlAndFace(String message) {
        SpannableStringBuilder messageSpan = new CommonURLClickHelper().formatURLMessage(mContext, message); // 转换样式后的信息内容
        faceTextView.setText(messageSpan);
        //  !!!!!!!!非常重要，这句必须加上，否则无法点击
        faceTextView.setMovementMethod(LinkMovementMethod.getInstance());
    }

    private void commonTextViewWithUrl(String message, String url) {
        mClickSpan = new TextLinkClickSpan(new URLClickListener(mContext, url));
        SpannableString spStr = new SpannableString(message);
        int begin = message.indexOf(url);
        int end = begin + url.length();
        spStr.setSpan(mClickSpan, begin, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        commonTextView.append(spStr);
        commonTextView.setMovementMethod(LinkMovementMethod.getInstance());
    }
}
